<template>
  <div id="PersonalHome">
    <a-row class="grid-demo" style="margin-bottom: 16px">
      <a-col flex="100px">
        <a-space size="large" direction="vertical">
          <a-avatar trigger-type="mask" :size="64" shape="square">
            <img alt="avatar" :src="avatarUrl" />
            <template #trigger-icon>
              <IconEdit />
            </template>
          </a-avatar>
        </a-space>
      </a-col>
      <a-col flex="auto">
        <div style="margin-top: 20px">
          <a-descriptions
            :data="data"
            title="用户信息"
            layout="vertical"
            bordered
          />
        </div>
      </a-col>
    </a-row>
    <a-collapse :show-expand-icon="false">
      <a-collapse-item :key="1">
        <template #extra>
          <a-tag size="large">编辑信息</a-tag>
        </template>
        <div>
          <a-form :model="form" @submit="handleSubmit">
            <a-row
              :gutter="16"
              class="grid-demo"
              style="margin-bottom: 16px"
              align="center"
            >
              <!-- 用户头像 -->
              <a-col :span="8">
                <a-form-item
                  field="userAvatar"
                  label="用户头像"
                  label-col-flex="100px"
                >
                  <a-input
                    v-model="form.userAvatar"
                    placeholder="请输入用户头像链接"
                  />
                </a-form-item>
              </a-col>
              <!-- 用户昵称 -->
              <a-col :span="8">
                <a-form-item
                  field="userName"
                  label="用户昵称"
                  label-col-flex="100px"
                >
                  <a-input
                    v-model="form.userName"
                    placeholder="请输入用户昵称"
                  />
                </a-form-item>
              </a-col>

              <!-- 用户简介 -->
              <a-col :span="8">
                <a-form-item
                  field="userProfile"
                  label="用户简介"
                  label-col-flex="100px"
                >
                  <a-input
                    v-model="form.userProfile"
                    placeholder="请输入用户简介"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item style="margin: auto 50%">
              <a-button html-type="submit" type="primary">提交</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-collapse-item>
    </a-collapse>
    <a-divider />
    <a-tabs type="rounded" size="large">
      <a-tab-pane key="1" title="收藏的帖子">
        <community-view :isFavour="true" />
      </a-tab-pane>
      <a-tab-pane key="2" title="提交的题目">
        <UserSubmitQuestionView />
      </a-tab-pane>
      <a-tab-pane key="3" title="创建的题目">
        <UserAddQuestionView />
      </a-tab-pane>
    </a-tabs>
    <a-divider />
  </div>
</template>

<script setup lang="ts">
import {
  PostFavourControllerService,
  PostQueryRequest,
  QuestionSubmitQueryRequest,
  UserControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { onMounted, ref } from "vue";
import CommunityView from "@/views/community/communityView.vue";
import UserAddQuestionView from "@/views/personalHome/UserAddQuestionView.vue";
import UserSubmitQuestionView from "@/views/personalHome/UserSubmitQuestionView.vue";

const dataList = ref([]);

const total = ref(0);

const data = ref([
  {
    label: "用户账号",
    value: "",
  },
  {
    label: "用户昵称",
    value: "",
  },
  {
    label: "用户角色",
    value: "",
  },
  {
    label: "创建时间",
    value: "",
  },
  {
    label: "更新时间",
    value: "",
  },
  {
    label: "用户简介",
    value: "",
  },
]);

//头像
const avatarUrl = ref("");

let form = ref({
  userAvatar: "",
  userName: "",
  userProfile: "",
});

const searchParams = ref<PostQueryRequest>({
  pageSize: 8,
  current: 1,
});
const searchParamsQuestion = ref<QuestionSubmitQueryRequest>({
  pageSize: 8,
  current: 1,
});

onMounted(() => {
  loadData();
  onMyPostStar();
});

const loadData = async () => {
  try {
    const userData = await UserControllerService.getLoginUserUsingGet();
    searchParamsQuestion.value.userId = userData.data?.id;
    //获取用户id
    const res = await UserControllerService.getUserByIdUsingGet(
      userData.data?.id
    );
    if (res.code === 0 && res.data) {
      const userData = res.data;

      // 更新用户头像
      avatarUrl.value =
        userData.userAvatar ||
        "https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp";

      // 更新 data 的内容
      data.value = [
        {
          label: "用户账号",
          value: userData.userAccount || "未提供",
        },
        {
          label: "用户昵称",
          value: userData.userName || "未提供",
        },

        {
          label: "用户角色",
          value: userData.userRole || "未提供",
        },
        {
          label: "创建时间",
          value: formatDateTime(userData.createTime) || "未提供",
        },
        {
          label: "更新时间",
          value: formatDateTime(userData.updateTime) || "未提供",
        },
        {
          label: "用户简介",
          value: userData.userProfile || "未填写",
        },
      ];
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
    message.error("加载失败，请稍后重试");
  }
};

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string | null): string => {
  if (!dateTime) return "";
  const date = new Date(dateTime);
  return date.toLocaleString(); // 转换为本地时间格式
};

/**
 * userAvatar?: string;
 *     userName?: string;
 *     userProfile?: string;
 */
const handleSubmit = async () => {
  const res = await UserControllerService.updateMyUserUsingPost(form.value);
  if (res.data) {
    message.success("更新成功");
  } else {
    message.error("更新失败，" + (res.message || "未知错误"));
  }
};

/**
 * 获取用户收藏的帖子
 * @param post
 *     content?: string;
 *     current?: number;
 *     favourUserId?: number;
 *     id?: number;
 *     notId?: number;
 *     orTags?: Array<string>;
 *     pageSize?: number;
 *     searchText?: string;
 *     sortField?: string;
 *     sortOrder?: string;
 *     tags?: Array<string>;
 *     title?: string;
 *     userId?: number;
 */
const onMyPostStar = async () => {
  // 收藏接口调用
  const res = await PostFavourControllerService.listMyFavourPostByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
    message.success("加载成功");
  } else {
    message.error("加载失败，" + res.message);
  }
};
</script>

<style scoped>
#questionView {
  max-width: 1280px;
  margin: 0 auto;
}

.card-demo {
  width: 360px;
  margin-left: 24px;
  transition-property: all;
}

.card-demo:hover {
  transform: translateY(-4px);
}
</style>
